package com.uyayo.oms.config;

import com.uyayo.system.monitor.interceptor.SqlExecuteInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

/**
 * MyBatis基础配置
 */
@Configuration
@EnableTransactionManagement// 启注解事务管理
@MapperScan(value={"com.**.mapper"})
public class MyBatisConfig{

    @Autowired
    private DataSource dataSource;

    @Bean(name="sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {

            bean.setPlugins(sqlExecuteInterceptor());
            bean.setMapperLocations(resolver.getResources("classpath:com/uyayo/**/mapper/*Mapper.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SqlExecuteInterceptor sqlExecuteInterceptor(){
        return new SqlExecuteInterceptor();
    }

}
